<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;

class UserController extends BaseController
{
    /**
     * 获取用户列表
     */
    public function index(Request $request)
    {
        try {
            $query = User::query();

            // 搜索条件
            if ($request->has('search')) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('username', 'like', "%{$search}%")
                      ->orWhere('phone', 'like', "%{$search}%");
                });
            }

            // 状态筛选
            if ($request->has('status')) {
                $query->where('status', $request->status);
            }

            // 分页
            $perPage = $request->get('per_page', 15);
            $users = $query->paginate($perPage);

            return $this->paginate($users, '获取用户列表成功');
        } catch (\Exception $e) {
            return $this->error('获取用户列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    public function show(User $user)
    {
        try {
            $user->load(['employee', 'roles.permissions', 'notifications' => function ($query) {
                $query->latest()->limit(5);
            }]);

            return $this->success($user, '获取用户信息成功');
        } catch (\Exception $e) {
            return $this->error('获取用户信息失败：' . $e->getMessage());
        }
    }

    /**
     * 创建用户
     */
    public function store(Request $request)
    {
        try {
            $data = $this->validateRequest($request, [
                'username' => 'required|string|min:2|max:50|unique:users',
                'phone' => 'required|string|regex:/^1[3-9]\d{9}$/|unique:users',
                'password' => 'required|string|min:6|max:20',
                'status' => 'sometimes|in:active,inactive,suspended,locked',
                'preferences' => 'sometimes|array',
            ]);

            // 获取所有输入数据（包括可选字段）
            $input = $request->all();

            // 创建用户
            $user = User::create([
                'username' => $data['username'],
                'phone' => $data['phone'],
                'password' => Hash::make($input['password']), // 直接从输入数据获取
                'status' => $data['status'] ?? $input['status'] ?? 'active',
                'preferences' => $data['preferences'] ?? $input['preferences'] ?? [
                    'theme' => 'light',
                    'language' => 'zh_CN',
                    'timezone' => 'Asia/Shanghai',
                ],
            ]);

            // 记录操作日志
            $this->logOperation('create', 'user', ['user_id' => $user->id, 'username' => $user->username]);

            return $this->success($user, '创建用户成功', 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            // 处理验证错误，提供用户友好的错误信息
            $errors = $e->errors();
            $friendlyErrors = [];

            foreach ($errors as $field => $messages) {
                foreach ($messages as $message) {
                    switch ($field) {
                        case 'username':
                            if (str_contains($message, 'unique')) {
                                $friendlyErrors[] = '用户名已存在，请使用其他用户名';
                            } elseif (str_contains($message, 'required')) {
                                $friendlyErrors[] = '用户名不能为空';
                            } elseif (str_contains($message, 'min')) {
                                $friendlyErrors[] = '用户名至少需要2个字符';
                            } elseif (str_contains($message, 'max')) {
                                $friendlyErrors[] = '用户名不能超过50个字符';
                            } else {
                                $friendlyErrors[] = '用户名格式不正确';
                            }
                            break;
                        case 'phone':
                            if (str_contains($message, 'unique')) {
                                $friendlyErrors[] = '手机号已被使用，请使用其他手机号';
                            } elseif (str_contains($message, 'regex')) {
                                $friendlyErrors[] = '请输入正确的手机号';
                            } elseif (str_contains($message, 'required')) {
                                $friendlyErrors[] = '手机号不能为空';
                            } else {
                                $friendlyErrors[] = '手机号格式不正确';
                            }
                            break;
                        case 'password':
                            if (str_contains($message, 'required')) {
                                $friendlyErrors[] = '密码不能为空';
                            } elseif (str_contains($message, 'min')) {
                                $friendlyErrors[] = '密码至少需要6个字符';
                            } elseif (str_contains($message, 'max')) {
                                $friendlyErrors[] = '密码不能超过20个字符';
                            } else {
                                $friendlyErrors[] = '密码格式不正确';
                            }
                            break;
                        case 'status':
                            $friendlyErrors[] = '用户状态值不正确，只能是正常、停用、暂停或锁定';
                            break;
                        case 'preferences':
                            $friendlyErrors[] = '用户偏好设置格式不正确';
                            break;
                        default:
                            $friendlyErrors[] = $message;
                            break;
                    }
                }
            }

            $errorMessage = implode('；', $friendlyErrors);
            return $this->error('创建用户失败：' . $errorMessage, 422, $errors);
        } catch (\Exception $e) {
            // 处理其他异常
            return $this->error('创建用户失败：服务器内部错误，请稍后重试', 500);
        }
    }

    /**
     * 更新用户信息
     */
    public function update(Request $request, User $user)
    {
        try {
            $data = $this->validateRequest($request, [
                'phone' => ['sometimes', 'string', 'regex:/^1[3-9]\d{9}$/', Rule::unique('users')->ignore($user->id)],
                'status' => 'sometimes|in:active,inactive,suspended,locked',
                'preferences' => 'sometimes|array',
            ]);

            // 更新用户
            $user->update($data);

            // 记录操作日志
            $this->logOperation('update', 'user', ['user_id' => $user->id, 'changes' => $data]);

            return $this->success($user, '更新用户信息成功');
        } catch (\Illuminate\Validation\ValidationException $e) {
            // 处理验证错误，提供用户友好的错误信息
            $errors = $e->errors();
            $friendlyErrors = [];

            foreach ($errors as $field => $messages) {
                foreach ($messages as $message) {
                    switch ($field) {
                        case 'phone':
                            if (str_contains($message, 'unique')) {
                                $friendlyErrors[] = '手机号已被使用，请使用其他手机号';
                            } elseif (str_contains($message, 'regex')) {
                                $friendlyErrors[] = '请输入正确的手机号';
                            } else {
                                $friendlyErrors[] = '手机号格式不正确';
                            }
                            break;
                        case 'status':
                            $friendlyErrors[] = '用户状态值不正确，只能是正常、停用、暂停或锁定';
                            break;
                        case 'preferences':
                            $friendlyErrors[] = '用户偏好设置格式不正确';
                            break;
                        default:
                            $friendlyErrors[] = $message;
                            break;
                    }
                }
            }

            $errorMessage = implode('；', $friendlyErrors);
            return $this->error('更新用户信息失败：' . $errorMessage, 422, $errors);
        } catch (\Exception $e) {
            // 处理其他异常
            return $this->error('更新用户信息失败：服务器内部错误，请稍后重试', 500);
        }
    }

    /**
     * 删除用户
     */
    public function destroy(User $user)
    {
        try {
            // 检查是否可以删除（比如检查是否有相关数据）
            if ($user->employee) {
                return $this->error('该用户有关联的员工信息，无法删除');
            }

            $user->delete();

            // 记录操作日志
            $this->logOperation('delete', 'user', ['user_id' => $user->id, 'username' => $user->username]);

            return $this->success(null, '删除用户成功');
        } catch (\Exception $e) {
            return $this->error('删除用户失败：' . $e->getMessage());
        }
    }

    /**
     * 修改密码
     */
    public function changePassword(Request $request, User $user)
    {
        try {
            $data = $this->validateRequest($request, [
                'old_password' => 'required|string',
                'new_password' => 'required|string|min:6|max:20|confirmed',
            ]);

            // 验证旧密码
            if (!Hash::check($data['old_password'], $user->password)) {
                return $this->error('旧密码不正确', 422);
            }

            // 更新密码
            $user->update([
                'password' => Hash::make($data['new_password']),
                'password_changed_at' => now(),
            ]);

            // 记录操作日志
            $this->logOperation('change_password', 'user', ['user_id' => $user->id]);

            return $this->success(null, '密码修改成功');
        } catch (\Exception $e) {
            return $this->error('密码修改失败：' . $e->getMessage());
        }
    }

    /**
     * 上传头像
     */
    public function uploadAvatar(Request $request, User $user)
    {
        try {
            $data = $this->validateRequest($request, [
                'avatar' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
            ]);

            // 删除旧头像
            if ($user->avatar && !filter_var($user->avatar, FILTER_VALIDATE_URL)) {
                Storage::disk('private')->delete($user->avatar);
            }

            // 上传新头像
            $file = $request->file('avatar');
            $filename = 'avatar_' . $user->id . '_' . time() . '.' . $file->getClientOriginalExtension();
            $path = $file->storeAs('avatars', $filename, 'private');

            // 更新用户头像
            $user->update(['avatar' => $path]);

            // 记录操作日志
            $this->logOperation('upload_avatar', 'user', ['user_id' => $user->id, 'filename' => $filename]);

            return $this->success([
                'avatar_url' => $user->avatar,
                'filename' => $filename,
            ], '头像上传成功');
        } catch (\Exception $e) {
            return $this->error('头像上传失败：' . $e->getMessage());
        }
    }

    /**
     * 更新用户偏好设置
     */
    public function updatePreferences(Request $request, User $user)
    {
        try {
            $data = $this->validateRequest($request, [
                'preferences' => 'required|array',
                'preferences.theme' => 'sometimes|in:light,dark',
                'preferences.language' => 'sometimes|string',
                'preferences.timezone' => 'sometimes|string',
            ]);

            $user->update($data);

            return $this->success($user->preferences, '偏好设置更新成功');
        } catch (\Exception $e) {
            return $this->error('偏好设置更新失败：' . $e->getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    public function me()
    {
        try {
            $user = $this->getCurrentUser();

            if (!$user) {
                return $this->error('用户未登录', 401);
            }

            $user->load(['employee', 'roles.permissions']);

            return $this->success($user, '获取当前用户信息成功');
        } catch (\Exception $e) {
            return $this->error('获取用户信息失败：' . $e->getMessage());
        }
    }
}
